var chooseLocation = requirePlugin('chooseLocation');
var app = getApp()
const dateUtil = require('../../utils/dateUtil')
Page({

  data: {
    movies: [],
    goods_info: [],
    goods_item: [],
	goods_list: '',
    request_num: 0,
    curpage: 1,
	xs: false,
	yt: false,
	yy: false,
    show: 0,
    is_show_time: 1,
    home1: '',
    key: '',
    favourite_goods: [],
    countDownList: [],
    actEndTimeList: [],
    swiper_image:"375",
	locationName: "" ,// 当前位置名称
	// 是否显示城市选择器
	showCityPicker: false,
	hotCities: ['北京', '上海', '广州', '深圳', '杭州', '成都', '武汉', '南京'],
	selectedCity: '',
	currentCity: '',
	statusArray: ['在线', '离线', '忙碌'],
	statusIndex: 0,

	  // 新增的弹窗相关数据
  showAddDesktopModal: false,          // 是否显示弹窗
  showOptionConfirmModal: false,       // 是否显示选项确认弹窗
  currentOption: '',                   // 当前选择的选项
  confirmText: '',                     // 确认弹窗的文本
  notToday: false,                     // 本日不再显示
  notForever: false,                   // 永久关闭
  addDesktopTimer: null                // 定时器
  },
  imgLoad:function(event){
    var imgwidth = event.detail.width,
      imgheight = event.detail.height,
      //宽高比  
      ratio = imgwidth / imgheight;
    var imgheight = 750 / ratio;
    this.setData({
      swiper_image: imgheight
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
	onLoad: function (options) {
		var that = this;
		var url = app.configData.shop.api_url + '/index.php?ctl=Index&met=hotArea&typ=json&ua=wap'
		wx.request({
		  url: url,
		  method: 'GET',
		  header: {
		    'content-type': 'application/json'
		  },
		  success: function (res) {
		    that.setData({
				hotCities: res.data.data
			})
		  }
		})
		// 尝试从全局数据读取位置
		if (app.globalData.selectedLocation) {
			that.setData({ locationName: app.globalData.selectedLocation.name,selectedCity: app.globalData.selectedLocation.name,currentCity: app.globalData.selectedLocation.name });
			that.xs()
		} else {
		  that.getCurrentLocation(); // 首次获取定位
		}
	},
	// 切换城市选择器显示状态
	  toggleCityPicker() {
	    this.setData({
	      showCityPicker: !this.data.showCityPicker
	    });
	  },
	  // 选择城市
	  selectCity(e) {
	    const city = e.currentTarget.dataset.city;
	    this.setData({
	      selectedCity: city,
			locationName: city,
	      showCityPicker: false,
	    });
		app.globalData.selectedLocation.name = city
		  if(this.data.xs){
		  	this.xs()
		  }
		  if(this.data.yt){
		  	this.yt()
		  }
		  if(this.data.yy){
		  	this.yy()
		  }
	  },
	  // 清空选择的城市
	  clearCity() {
	    this.setData({
	      selectedCity: '',
			locationName: '',
	    });
		// 存储到全局方便其他页面使用
		app.globalData.selectedLocation = {
		  name: ''
		};
	  },
	// 获取当前位置
	getCurrentLocation() {
		wx.getLocation({
			type: 'gcj02',
			success: (res) => {
				let {latitude, longitude} = res
			  // 逆地理编码获取地名（需自行调用腾讯地图API，此处简化）
			  // 使用经纬度获取具体地址信息
			  wx.request({
				  url: 'https://apis.map.qq.com/ws/geocoder/v1/',
				  data: {
					  location: `${latitude},${longitude}`,
					  key: 'F53BZ-D7JW7-NDOX3-PJQDM-3EXP6-NWBMO', // 需要替换为实际的腾讯地图key
					  get_poi: 0
				  },
				  success: (result) => {
					  if (result.data.status === 0) {
							let address = result.data.result.address_component.city
							this.setData({ locationName: address,selectedCity:address,currentCity:address });
							// 存储到全局方便其他页面使用
							app.globalData.selectedLocation = {
							  name: result.data.result.address_component.city,
							  address: result.data.result.address,
							  latitude: result.data.result.location.lat,
							  longitude: result.data.result.location.lng
							};
							this.xs()
					  }
				  }
			  })
			},
			fail: (err) => {
			  this.handleLocationPermission();
			}
		});
	},
	// 打开地图选点
	handleChooseLocation() {
	    const key = "F53BZ-D7JW7-NDOX3-PJQDM-3EXP6-NWBMO"; // 替换为实际Key
	    const referer = "铧佗帮护";
	    wx.navigateTo({
	      url: `plugin://chooseLocation/index?key=${key}&referer=${referer}`
	    });
	},
	// 处理定位权限
	handleLocationPermission() {
		wx.getSetting({
		  success: (res) => {
			if (!res.authSetting['scope.userLocation']) {
			  wx.showModal({
				title: '需要位置权限',
				content: '请授权位置信息以使用定位功能',
				success: (res) => {
				  if (res.confirm) wx.openSetting();
				}
			  });
			}
		  }
		});
	},
  //小时排序
  xs: function () {
    var that = this
    var url = app.configData.shop.api_url + '/index.php?ctl=Goods_Goods&met=goodslist&typ=json&ua=wap&pagesize=10'
    var data = { curpage: 1, service_type: '按小时', locationName: that.data.locationName }
    wx.request({
      url: url,
      method: 'GET',
      data: data,
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        that.setData({
          goods_list: res.data.data.items,
          curpage: 1,
          request_num: 0,
          xs: true,
          yt: false,
          yy: false
        });
      }
    })
  },
  //一天
  yt: function () {
    var that = this
    var url = app.configData.shop.api_url + '/index.php?ctl=Goods_Goods&met=goodslist&typ=json&ua=wap&pagesize=10'
    var data = { curpage: 1, service_type: '按天', locationName: that.data.locationName }
    wx.request({
      url: url,
      method: 'GET',
      data: data,
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        that.setData({
          goods_list: res.data.data.items,
          curpage: 1,
          request_num: 0,
          xs: false,
          yt: true,
          yy: false
        });
  
      }
    })
  },
  //一月
  yy: function () {
    var that = this
    var actorder = that.data.actorder
    var url = app.configData.shop.api_url + '/index.php?ctl=Personal_Resume&met=resumeList&typ=json&ua=wap&pagesize=10'
    var data = { curpage: 1, locationName: that.data.locationName}
    wx.request({
      url: url,
      method: 'GET',
      data: data,
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
		const goods_list = res.data.data.items.map((item, index) => {
			
						item.user_info.userName = item.user_info.userName.charAt(0) + '**'
		            return {
		              ...item,
		              age: dateUtil.getYearDiff(item.user_info.birthDate) || 0,
					  gender: item.user_info.gender == 1 ? '女' : '男',
		              address: item.user_info.region || '' // 格式化价格
		            };
		          });
        that.setData({
          goods_list: goods_list,
          curpage: 1,
          request_num: 0,
          xs: false,
          yt: false,
          yy: true,
        });
      }
	  
    })
  },
  //跳转至商品详情页
  goProduct: function (e) {
    var goods_id = e.currentTarget.dataset.goods_id
	wx.navigateTo({
	  url: '../product_detail/product_detail?goods_id=' + goods_id
	})
  },
  goProduct2: function (e) {
    var goods_id = e.currentTarget.dataset.goods_id
	var key = wx.getStorageSync('key')
	if (key) {
		wx.navigateTo({
		  url: '../resume_detail/resume_detail?goods_id=' + goods_id
		})
	} else {
		wx.showModal({
			title: '登录提示',
			content: '此功能需要登录后才能使用',
			confirmText: '去登录',
			cancelText: '再逛逛',
			success: (res) => {
			  if (res.confirm) {
				wx.navigateTo({
				  url: `/pages/authorize_login/authorize_login`
				});
			  } else {
				wx.switchTab({ url: '/pages/index/index' });
			  }
			}
		});
	}
	
  },
  callMe: function (e) {
  	var mobile = e.currentTarget.dataset.mobile
    wx.makePhoneCall({
      phoneNumber: mobile,
    });
  },
  /**
     * 页面上拉触底事件的处理函数
     */
  onReachBottom: function () {
    var that = this
    var curpage = that.data.curpage
    var datas = ''
    if (that.data.request_num == 1) {
      return false
    }
    curpage++
    if (that.data.xs == true) {
      datas = { curpage: curpage, service_type: '按小时', locationName: that.data.locationName }
	  wx.request({
	    url: app.configData.shop.api_url + '/index.php?ctl=Goods_Goods&met=goodslist&typ=json&ua=wap&pagesize=10',
	    method: 'GET',
	    data: datas,
	    header: {
	      'content-type': 'application/json'
	    },
	    success: function (res) {
	    
	      if (res.data.data.items.length > 0) {
	        var goods_list = that.data.goods_list
	        for (var z in res.data.data.items) {
	          goods_list.push(res.data.data.items[z])
	        }
	        that.setData({
	          goods_list: goods_list,
	          curpage: curpage
	        })
	      } else {
	        that.setData({
	          request_num: 1
	        })
	      }
	    }
	  })
    } else if (that.data.yt == true) {
      datas = { curpage: curpage, service_type: '按天', locationName: that.data.locationName }
	  wx.request({
	    url: app.configData.shop.api_url + '/index.php?ctl=Goods_Goods&met=goodslist&typ=json&ua=wap&pagesize=10',
	    method: 'GET',
	    data: datas,
	    header: {
	      'content-type': 'application/json'
	    },
	    success: function (res) {
	    
	      if (res.data.data.items.length > 0) {
	        var goods_list = that.data.goods_list
	        for (var z in res.data.data.items) {
	          goods_list.push(res.data.data.items[z])
	        }
	        that.setData({
	          goods_list: goods_list,
	          curpage: curpage
	        })
	      } else {
	        that.setData({
	          request_num: 1
	        })
	      }
	    }
	  })
    } else {
      datas = { curpage: curpage, locationName: that.data.locationName}
	  wx.request({
	    url: app.configData.shop.api_url + '/index.php?ctl=Personal_Resume&met=resumeList&typ=json&ua=wap&pagesize=10',
	    method: 'GET',
	    data: datas,
	    header: {
	      'content-type': 'application/json'
	    },
	    success: function (res) {
	    
	      if (res.data.data.items.length > 0) {
	        var goods_list = that.data.goods_list
	        for (var z in res.data.data.items) {
	          goods_list.push(res.data.data.items[z])
	        }
	        that.setData({
	          goods_list: goods_list,
	          curpage: curpage
	        })
	      } else {
	        that.setData({
	          request_num: 1
	        })
	      }
	    }
	  })
    }
  
    
  },
onShow: function() {
  var that = this;
  var good_info = [];
  var goods_item = [];
  var home1 = [];
  var slider_list = [];
  var key = wx.getStorageSync('key');
  var content_info = [];
  let endTimeList = [];
  
  // 检查并显示添加桌面引导弹窗
  that.checkAndShowAddDesktopModal();
  
  wx.request({
    url: app.configData.shop.api_url + '/index.php?ctl=Index&met=wxapp_index&typ=json&ua=wap',
    method: 'GET',
    data: {
      type_wxapp: 'wxapp'
    },
    header: {
      'content-type': 'application/json'
    },
    success: function(res) {

      var arr = res.data.data.module_data;
      var favourite_goods = res.data.data.favourite_goods;
      // 猜你喜歡
      if (favourite_goods) {
        for (var i in favourite_goods) {
          favourite_goods[i].goods_name = favourite_goods[i].goods_name.substring(0, 5);
        }
      }

      if (res.data.status == 200) {
        for (var i in arr) {
          for (var s in arr[i]) {
            if (s == 'goodsB') {
              for (var z in arr[i][s].item) {
                arr[i][s].item[z].goods_name = arr[i][s].item[z].goods_name.substring(0, 5);
              }
            }
          }
        }
        that.setData({
          goods_info: arr,
          is_show_time: 0,
          home1: home1,
          key: key,
          favourite_goods: favourite_goods,

        });
      } else {
        that.setData({
          goods_info: goods_item,
          is_show_time: 0,
          home1: home1,
          key: key,
          favourite_goods: favourite_goods,

        });
      }
     
      
    }
  })
  
  const selectedLocation = chooseLocation.getLocation();
  if (selectedLocation) {
    this.setData({ locationName: selectedLocation.city || selectedLocation.address });
    // 存储到全局方便其他页面使用
    app.globalData.selectedLocation = {
      name: selectedLocation.city,
      address: selectedLocation.address,
      latitude: selectedLocation.latitude,
      longitude: selectedLocation.longitude
    };
    if(this.data.xs){
      this.xs()
    }
    if(this.data.yt){
      this.yt()
    }
    if(this.data.yy){
      this.yy()
    }
    
  }
},

  timeFormat(param) { //小于10的格式化函数
    return param < 10 ? '0' + param : param;
  },

  dj: function(e) {
    var that = this
    var data = e.currentTarget.dataset.data
    var types = e.currentTarget.dataset.type
    if (data) {
      switch (types) {
        case 'url':
          wx.navigateTo({
            url: '../web_view/web_view?url=' + encodeURIComponent(data),
          });
          break;
        case 'goods':
          wx.navigateTo({
            url: '../product_detail/product_detail?goods_id=' + data,
          });
          break;
        case 'keyword':
          wx.navigateTo({
            url: '../search_list/search_list?content=' + data,
          });
          break;
        default:
			if(data == '/pages/release_requirement/release_requirement') {
				var key = wx.getStorageSync('key')
				  if (key) {
					wx.navigateTo({
						url: data,
					});
				  } else {
					  wx.showModal({
						title: '登录提示',
						content: '此功能需要登录后才能使用',
						confirmText: '去登录',
						cancelText: '再逛逛',
						success: (res) => {
						  if (res.confirm) {
							wx.navigateTo({
							  url: `/pages/authorize_login/authorize_login`
							});
						  } else {
							wx.switchTab({ url: '/pages/index/index' });
						  }
						}
					  });
				  }
			} else {
				wx.navigateTo({
				  url: data,
				});
			}
          break;

      }
    }


  },


  djr: function (e) {
    var that = this
    var data = e.currentTarget.dataset.data
    var types = e.currentTarget.dataset.type
    if (data) {
      wx.navigateTo({
        url: '../web_view/web_view?url=' + encodeURIComponent(data),
      });
    }


  },
  //事件处理函数
  bindViewTap: function(e) {
    wx.navigateTo({
      // url: '../toastDemo/toast'
      url: '../search/search'
    })
  },

  bindhref: function(e) {
    app.goTop()
    this.setData({
      show: 0
    })
  },
  //一键到顶
  onPageScroll: function(e) {
    // 获取滚动条当前位置
    var that = this
    wx.getSystemInfo({
      success: function(res) {

        if (e.scrollTop + res.windowHeight > res.windowHeight) {
          that.setData({
            show: 1
          })
        } else {
          that.setData({
            show: 0
          })
        }
      },
    })
  },
  onShareAppMessage: function(res) {
    return {
      desc: '首页',
      success: function(res) {}
    }
  },
  //下拉刷新
  onPullDownRefresh: function() {
    var that = this
    wx.showToast({
      title: '加载中', //提示信息
      icon: 'loading', //成功显示图标
      duration: 2000 //时间
    })
    that.onShow()
    wx.stopPullDownRefresh()

  },

  countDown(objs) {
    //倒计时函数
    // 获取当前时间，同时得到活动结束时间数组
    let newTime = new Date().getTime();
    let goods_info = this.data.goods_info;

    // for (var i in goods_info){
    //   if (goods_info[i]){
    //     for (var j in goods_info[i]){
    //       if (j == 'activityA'){
    //         for (var z in goods_info[i][j].item.content_info){
    //           if (goods_info[i][j].item.content_info[z]){
    //             for (var w in goods_info[i][j].item.content_info[z]){
    //               if (goods_info[i][j].item.content_info[z][w]){

    //                 let endTime = new Date(goods_info[i][j].item.content_info[z][w].goods_end_time).getTime();
    //                 let obj = null;
    //                 // 如果活动未结束，对时间进行处理
    //                 if (endTime - newTime > 0) {
    //                   let time = (endTime - newTime) / 1000;
    //                   // 获取天、时、分、秒
    //                   let day = parseInt(time / (60 * 60 * 24));
    //                   let hou = parseInt(time % (60 * 60 * 24) / 3600);
    //                   let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
    //                   let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
    //                   obj = {
    //                     day: this.timeFormat(day),
    //                     hou: this.timeFormat(hou),
    //                     min: this.timeFormat(min),
    //                     sec: this.timeFormat(sec)
    //                   }
    //                 } else {//活动已结束，全部设置为'00'
    //                   obj = {
    //                     day: '00',
    //                     hou: '00',
    //                     min: '00',
    //                     sec: '00'
    //                   }
    //                 }
    //                 goods_info[i][j].item.content_info[z][w].goods_end_times = obj;

    //               }
    //             }
    //           }
    //         }
    //       }
    //     }
    //   }
    // }

    // this.setData({
    //   goods_info: goods_info
    // })
    // setTimeout(this.countDown, 1000);

  },
  countDowns: function(objs, i, s, w, z, arr) {

    let end_time = objs;
    //倒计时函数
    // 获取当前时间，同时得到活动结束时间数组
    let newTime = new Date().getTime();

    let endTime = new Date(end_time).getTime();
    let obj = null;
    // 如果活动未结束，对时间进行处理
    if (endTime - newTime > 0) {
      let time = (endTime - newTime) / 1000;
      // 获取天、时、分、秒
      let day = parseInt(time / (60 * 60 * 24));
      let hou = parseInt(time % (60 * 60 * 24) / 3600);
      let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
      let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
      obj = {
        day: this.timeFormat(day),
        hou: this.timeFormat(hou),
        min: this.timeFormat(min),
        sec: this.timeFormat(sec)
      }
    } else { //活动已结束，全部设置为'00'
      obj = {
        day: '00',
        hou: '00',
        min: '00',
        sec: '00'
      }
    }

    arr[i][s].item.content_info[w][z].goods_end_times = obj;
    this.setData({
      goods_info: arr,
    });
    console.log(arr)
    //setTimeout(this.countDowns(objs, i, s, w, z, arr), 10000);
  },
  
  // 检查并显示添加桌面引导弹窗
checkAndShowAddDesktopModal: function() {
  var that = this;
  
  // 检查是否永久关闭
  var neverShowAgain = wx.getStorageSync('never_show_add_desktop_modal');
  if (neverShowAgain) {
    return;
  }
  
  // 检查今日是否不再显示
  var today = new Date().toDateString();
  var notShowToday = wx.getStorageSync('not_show_add_desktop_today');
  if (notShowToday === today) {
    return;
  }
  
  // 清除之前的定时器
  if (that.data.addDesktopTimer) {
    clearTimeout(that.data.addDesktopTimer);
  }
  
  // 设置5秒后显示弹窗
  var timer = setTimeout(function() {
    that.setData({
      showAddDesktopModal: true
    });
  }, 10000);
  
  that.setData({
    addDesktopTimer: timer
  });
},

// 隐藏弹窗
hideAddDesktopModal: function() {
  this.setData({
    showAddDesktopModal: false
  });
},

// 切换选项
toggleOption: function(e) {
  var option = e.currentTarget.dataset.option;
  if (option === 'today') {
    this.setData({
      notToday: !this.data.notToday,
      notForever: false // 如果选择今日不再显示，取消永久关闭的选择
    });
  } else if (option === 'forever') {
    this.setData({
      notForever: !this.data.notForever,
      notToday: false // 如果选择永久关闭，取消今日不再显示的选择
    });
  }
},

// 弹窗确认（是）
onModalConfirm: function() {
  var that = this;
  
  // 处理用户选择
  if (that.data.notToday) {
    var today = new Date().toDateString();
    wx.setStorageSync('not_show_add_desktop_today', today);
  }
  
  if (that.data.notForever) {
    wx.setStorageSync('never_show_add_desktop_modal', true);
  }
  
  // 隐藏弹窗
  that.setData({
    showAddDesktopModal: false
  });
  
  // 跳转到引导页面
  wx.navigateTo({
    url: '/pages/add_to_desktop_guide/add_to_desktop_guide'
  });
},

// 弹窗取消（否）
onModalCancel: function() {
  var that = this;
  
  // 处理用户选择
  if (that.data.notToday) {
    var today = new Date().toDateString();
    wx.setStorageSync('not_show_add_desktop_today', today);
  }
  
  if (that.data.notForever) {
    wx.setStorageSync('never_show_add_desktop_modal', true);
  }
  
  // 隐藏弹窗
  that.setData({
    showAddDesktopModal: false
  });
},

onHide: function() {
  var that = this;
  // 清除定时器
  if (that.data.addDesktopTimer) {
    clearTimeout(that.data.addDesktopTimer);
    that.setData({
      addDesktopTimer: null
    });
  }
},

onUnload: function() {
  var that = this;
  // 清除定时器
  if (that.data.addDesktopTimer) {
    clearTimeout(that.data.addDesktopTimer);
    that.setData({
      addDesktopTimer: null
    });
  }
},

// 显示选项确认弹窗
showOptionConfirm: function(e) {
  var option = e.currentTarget.dataset.option;
  var confirmText = '';
  
  if (option === 'today') {
    confirmText = '确认今日不再显示该弹窗？';
  } else if (option === 'forever') {
    confirmText = '确认永久关闭该提醒？此操作不可撤销。';
  }
  
  this.setData({
    showOptionConfirmModal: true,
    currentOption: option,
    confirmText: confirmText
  });
},

// 隐藏选项确认弹窗
hideOptionConfirmModal: function() {
  this.setData({
    showOptionConfirmModal: false,
    currentOption: '',
    confirmText: ''
  });
},

// 确认选项设置
confirmOption: function() {
  var that = this;
  var option = that.data.currentOption;
  
  if (option === 'today') {
    var today = new Date().toDateString();
    wx.setStorageSync('not_show_add_desktop_today', today);
    that.setData({
      notToday: true,
      notForever: false
    });
    wx.showToast({
      title: '今日不再提醒',
      icon: 'success',
      duration: 1500
    });
  } else if (option === 'forever') {
    wx.setStorageSync('never_show_add_desktop_modal', true);
    that.setData({
      notForever: true,
      notToday: false
    });
    wx.showToast({
      title: '已永久关闭提醒',
      icon: 'success',
      duration: 1500
    });
  }
  
  // 隐藏确认弹窗和主弹窗
  that.setData({
    showOptionConfirmModal: false,
    showAddDesktopModal: false,  // 添加这行关闭主弹窗
    currentOption: '',
    confirmText: ''
  });
},

})